<?php

namespace fankers\lib\wx;

use fankers\api\wxApi;
use fankers\config\WxConfig;
use fankers\helper\Log;
use fankers\lib\Base;

class Wx extends Base
{
    public function __construct($params)
    {
        return parent::__construct($params);
    }
    ## come on 授权code
    public function start()
    {
        $oauth  = WxApi::OAUTH_URI;## 授权地址
        $params['appid']  = WxConfig::APP_ID;
        $params['redirect_uri'] = $this->redirect;
        $params['response_type'] = WxConfig::RESPONSE_TYPE;
        $params['scope']  = WxConfig::SCOPE;
        $params['state']  = $this->randCharts(32);

        ## http_build_query 有urlencode的功能
        $url = $oauth."?".http_build_query($params).'#wechat_redirect';

        if (!isset($_GET['code'])) {
            header('Location:'.$url);
            exit();
        }
    }

    ## 获取 access_token
    public function token($params)
    {
        $data = [
            'appid' => WxConfig::APP_ID,
            'secret' => WxConfig::APP_SECRET,
            'grant_type' => WxConfig::GRANT_TYPE
        ];

        if (is_array($params)) {
            $data = array_merge($data,$params);
        }
//        Log::debug($data,'/tmp/fkk_accesstoken_oauth');
        $tokenUrl = WxApi::ACCESS_TOKEN;#token 地址

        $tokenInfo = $this->http->get($tokenUrl,$data);
//        Log::debug($tokenInfo,'/tmp/fkk_accesstoken_oauth');
        return $this->http->parseJSON($tokenInfo);

    }

    ## 刷新access_token
    public function refreshToken($params)
    {
//      $params = ['refresh_token' => '']
        $data = [
            'appid' => WxConfig::APP_ID,
            'grant_type' => WxConfig::GRANT_TYPE_REFRESH
        ];

        if (is_array($params)) {
            $data = array_merge($data,$params);
        }

        $tokenUrl = WxApi::REFRESH_TOKEN; # 刷新token 地址

        $tokenInfo = $this->http->get($tokenUrl,$data);

        return $this->http->parseJSON($tokenInfo);
        
    }

    ## 获取用户信息
    public function info($params)
    {
        $infoUrl = WxApi::USER_INFO;

        $userInfo = $this->http->get($infoUrl,$params);

        return $this->http->parseJSON($userInfo);
    }

    ## 校验授权信息是否有效
    public function isvalid($params)
    {
        $validUrl = WxApi::IS_VALID;
        $validInfo = $this->http->get($validUrl,$params);

        return $this->http->parseJSON($validInfo);
    }
}